from django.shortcuts import render, redirect
from web import models
from web.utils.pagination import Pagination
import tkinter
import qrcode
from django import forms

from web.views.message import MessageModelForm1


def mainbook_list(request):
    """预约列表"""
    queryset = models.Bookinfo.objects.filter().all()

    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, "mainbook_list.html", context)

def mainbook_listdelete(request, nid):
    """ 删除预约（ModelForm版本）"""
    models.Bookinfo.objects.filter(id=nid).delete()
    return redirect('/mainbook/list/')

filename = '二维码.png'
def mk_qrcode(request, nid):
    q = qrcode.QRCode()
    content = models.Bookinfo.objects.filter(id=nid).first()
    q.add_data(content)
    q.make()
    img = q.make_image()
    img.save(filename)
    root = tkinter.Tk()
    root.title('信息码')
    canvas = tkinter.Canvas(root, width=400, height=400, bg='white')
    img = tkinter.PhotoImage(file=filename)
    canvas.create_image(200, 200, image=img)
    canvas.pack()
    root.mainloop()
    return redirect('/mybookInfo/')

class ScenicModelForm(forms.ModelForm):
    class Meta:
        model = models.Bookinfo
        fields = '__all__'
        # widgets = {
        #     "email": forms.EmailInput(attrs={"class": "form-control", "placeholder": "邮箱"}),
        #
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "email":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def package_details(request):
    """ 预定风景（ModelForm版本）"""
    if request.method == "GET":
        form = ScenicModelForm()
        form = MessageModelForm1(data=request.POST, files=request.FILES)

        return render(request, 'package-details1.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = ScenicModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/index/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'package-details1.html', {"form": form})
